<?php
namespace wxuserinfo;

class Wxuserinfo
{
    //第一步由后台完成获取code值
    public function index($params){
        if($params['scope']=='snsapi_userinfo'){
            $redirect_uri=url('pay/wxuserinfo/userinfo','','',true);
        }
        else{
            $redirect_uri=url('pay/wxuserinfo/base','','',true);
        }
        $redirect_uri=urlencode($redirect_uri);
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . config('wxpay.APPID') . '&redirect_uri='.$redirect_uri .'?return_url='. $params['return_url'] . '&response_type=code&scope=' . $params['scope']. '#wechat_redirect';
        Header("Location: $url");
    }

    //获得code值之后的处理方法 并返回结果
    public function requireCode($params){
        $code = $params['code'];
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wxpay.APPID').'&secret='.config('wxpay.APPSECRET').'&code='.$code.'&grant_type=authorization_code';
        $res = http_get($url);
        $res=json_decode($res,true);
        if(!isset($res['errcode'])&&$params['scope']=='snsapi_userinfo'){
            $userinfo ='https://api.weixin.qq.com/sns/userinfo?access_token='.$res['access_token'].'&openid='.$res['openid'].'&lang=zh_CN';
            $data = http_get($userinfo);
            $data=json_decode($data,true);
        }
        else{
            $data = json_encode($res);
        }
        return $data;
    }


}